import { getApiHostname } from '~/utils';

// 仅SSR使用

interface RequestType<T> {
    code?: number;
    data?: T;
    message?: string;
}

const request = async <T>(
    url: string,
    method: 'get' | 'post' | 'put' = 'get',
    params = {},
    isLazy = true
) => {
    const options = {
        baseURL: getApiHostname(),
        headers: useHeader().value,
        query: method === 'get' ? params : {},
        params: method !== 'get' ? params : {},
    };
    try {
        const { data, error } = isLazy
            ? await useLazyFetch<RequestType<T>>(url, options)
            : useFetch(url, options);
        if (error.value) {
            createError(error.value);
        }
        const response = data.value as RequestType<T>;
        if (response?.code !== 200) {
            createError(response?.message || response?.code?.toString() || 'Unknown request error');
        }
        return (response?.data ?? response) as T;
    } catch (err) {
        return Promise.reject(err);
    }
};

export const useLazyRequest = <T>(
    url: string,
    method: 'get' | 'post' | 'put' = 'get',
    params?: Record<string, any>
) => {
    return () => request<T>(url, method, params, true);
};
export const useRequest = <T>(
    url: string,
    method: 'get' | 'post' | 'put' = 'get',
    params?: Record<string, any>
) => {
    return () => request<T>(url, method, params, false);
};
